package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"reflect"
)

type StreamInfo struct {
	App              string `json:"app"`
	Stream           string `json:"stream"`
	Schema           string `json:"schema"`
	ReaderCount      int    `json:"readerCount"`
	TotalReaderCount int    `json:"totalReaderCount"`
}

type StreamList struct {
	Data []StreamInfo `json:"data"`
}

func getCount(app string, stream string, result []byte) int {
	var ret int = 0
	var list StreamList
	err := json.Unmarshal(result, &list)
	if err != nil {
		log.Println("JsonToMapDemo err: ", err)
		return 0
	}
	fmt.Println("----------------------------------------------------------")
	for _, value := range list.Data {
		log.Println(value)
		if value.App == app && value.Stream == stream {

			if value.TotalReaderCount > 0 {
				log.Println("TotalReaderCount:", value.TotalReaderCount)
				return value.TotalReaderCount
			} else {
				log.Println("ReaderCount:", value.ReaderCount)
				ret += value.ReaderCount
			}
		}
	}
	fmt.Println("----------------------------------------------------------")
	return ret
}

func readFileFromPath(path string) []byte {
	content, err := ioutil.ReadFile(path)
	if err != nil {
		log.Println(err)
	}
	return content
}

func main() {
	log.SetPrefix("[Map TEST] ")
	log.SetFlags(log.Llongfile | log.Ltime | log.Ldate)
	fmt.Println("----------------------------------------------------------")
	data := readFileFromPath("data.json")
	log.Println(string(data))
	fmt.Println("----------------------------------------------------------")
	count := getCount("test", "test", data)
	log.Println("观看人数：", count)
	fmt.Println("----------------------------------------------------------")
	var mapResult map[string]interface{}
	err := json.Unmarshal(data, &mapResult)
	if err != nil {
		fmt.Println("JsonToMapDemo err: ", err)
	}
	log.Println(reflect.TypeOf(mapResult).Kind())
	log.Println(mapResult)
	fmt.Println("----------------------------------------------------------")
	// var count int = 0
	if mapData, ok := mapResult["data"]; ok {
		m1 := mapData.([]interface{})
		for _, v := range m1 {
			m2 := v.(map[string]interface{})
			if v1, ok := m2["readerCount"].(float64); ok {
				log.Println(v1)
			}
		}
	} else {
		log.Println("ERROR1")
	}
	fmt.Println("----------------------------------------------------------")
}
